package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import jakarta.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;


//JPA配置
@Configuration
// 开启JPA仓库扫描（指定repository包路径）
@EnableJpaRepositories(basePackages = "com.example.demo.repository")
public class JpaConfig {

    private final DataSource dataSource;

    // 自动注入上面配置的DataSource
    public JpaConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    // 配置实体管理器工厂
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        // 指定实体类包路径（替代persistence.xml中的<class>）
        em.setPackagesToScan("com.example.demo.model");
        // 使用Hibernate作为JPA实现
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        // 配置Hibernate属性（替代hibernate.cfg.xml）
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update"); // 自动建表
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
        properties.setProperty("hibernate.show_sql", "true"); // 显示SQL
        em.setJpaProperties(properties);

        return em;
    }

    // 配置事务管理器
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}